import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, InputNumber, message, Modal, Row, Select} from "antd";
import type {Result} from "@/types/result";
import chargeApi from "@/api/chargeApi.ts";
import {Charge} from "@/types/resp/charge";
import BuildingSelector from "@/pages/building/BuildingSelector.tsx";
import RoomSelector from "@/pages/room/RoomSelector.tsx";

interface ChargeAddProps {
  visible: boolean;
  id: number;
  onCloseChargeAdd: () => void;
}

const ChargeAdd: React.FC<ChargeAddProps> = ({visible, id, onCloseChargeAdd}) => {

  const [form] = Form.useForm<Charge>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    buildingName: [
      { required: true, message: '请输入楼栋名称' }
    ],
    roomNumber: [
      { required: true, message: '请输入单元房号' }
    ],
    chargeType: [
      { required: true, message: '请输入收费类型' }
    ],
  };

  let chargeForm: Partial<Charge> = {}

  const [title, setTitle] = useState('新增收费信息');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑收费信息')
      initChargeFormById(id)
    } else {
      setTitle('新增收费信息')
      form.resetFields();
    }
  }, [visible]);

  const initChargeFormById = async (id: number) => {
    const resp: Result<Charge> = await chargeApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      chargeForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let charge2Save:Charge = form.getFieldsValue()
      if (id) {
        charge2Save = Object.assign(chargeForm, charge2Save)
      }
      const resp: Result<void> = await chargeApi.save(charge2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增收费信息')
    form.resetFields();
  };
  
  const [buildingSelectorVisible, setBuildingSelectorVisible] = useState(false);
  const findBuilding = () => {
    setBuildingSelectorVisible(true);
  }
  const handleBuildingSelected = (selectedBuilding: { buildingId?: number; buildingName?: string; }) => {
    setBuildingSelectorVisible(false)
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      buildingId: selectedBuilding['buildingId'],
      buildingName: selectedBuilding['buildingName'],
      }));
    }
  };
  const handleCloseBuildingSelector = () => {
    setBuildingSelectorVisible(false)
  };
  const [roomSelectorVisible, setRoomSelectorVisible] = useState(false);
  const findRoom = () => {
    setRoomSelectorVisible(true);
  }
  const handleRoomSelected = (selectedRoom: { roomId?: number; roomNumber?: string; }) => {
    setRoomSelectorVisible(false)
    if (selectedRoom && 'roomId' in selectedRoom) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      roomId: selectedRoom['roomId'],
      roomNumber: selectedRoom['roomNumber'],
      }));
    }
  };
  const handleCloseRoomSelector = () => {
    setRoomSelectorVisible(false)
  };

  const onBack = () => {
    onCloseChargeAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseChargeAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="chargeForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="buildingName" label="楼栋名称" rules={rules.buildingName}>
              <Input.Search placeholder="请选择楼栋名称" onSearch={findBuilding} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="roomNumber" label="单元房号" rules={rules.roomNumber}>
              <Input.Search placeholder="请选择单元房号" onSearch={findRoom} readOnly={true} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="chargeType" label="收费类型" rules={rules.chargeType}>
              <Select placeholder="请选择收费类型" options={[
                { value: 10, label: <span>物业费</span> },
                { value: 20, label: <span>水费</span> },
                { value: 30, label: <span>电费</span> },
                { value: 40, label: <span>煤气费</span> }
              ]} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="billingCycle" label="收费周期类型">
              <Input maxLength={255} placeholder="请输入收费周期类型"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="billingStartDate" label="收费周期开始时间">
              <DatePicker/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="billingEndDate" label="收费周期结束时间">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="amount" label="金额">
              <InputNumber min={1} max={1} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="lateFee" label="滞纳金金额">
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="dueDate" label="应付截止日期">
              <DatePicker/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="paymentDate" label="实际支付日期">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="paymentStatus" label="支付状态">
              <Select placeholder="请选择支付状态" options={[
                { value: 10, label: <span>未支付</span> },
                { value: 20, label: <span>已支付</span> },
                { value: 90, label: <span>已作废</span> }
              ]} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <BuildingSelector visible={buildingSelectorVisible} onBuildingSelected={handleBuildingSelected} onCloseBuildingSelector={handleCloseBuildingSelector} />
      <RoomSelector visible={roomSelectorVisible} onRoomSelected={handleRoomSelected} onCloseRoomSelector={handleCloseRoomSelector} />
    </Modal>
  )
}

export default ChargeAdd;
